<template>
  <a-row :gutter="[16, 16]" class="search">
    <a-col :span="4">
      <a-input v-model:value="searchInfo.title" placeholder="博客标题" />
    </a-col>
    <a-col :span="4">
      <a-select
        v-model:value="searchInfo.sort"
        placeholder="博客分类"
        style="width: 100%"
      >
        <a-select-option
          v-for="item of sortList"
          :value="item.id"
          :key="item.id"
          >{{ item.name }}</a-select-option
        >
      </a-select>
    </a-col>
    <a-col :span="4" class="btn">
      <a-button :icon="h(SearchOutlined)" type="primary" @click="search"
        >搜索
      </a-button>
      <a-button :icon="h(RedoOutlined)" @click="restSearch">重置</a-button>
    </a-col>
  </a-row>

  <a-row style="display: flex; align-items: center; gap: 15px; margin: 15px 0">
    <a-popconfirm
      cancel-text="取消"
      ok-text="还原"
      title="该操作会还原这些博客，是否还原?"
      @confirm="reviewFunction(toRaw(state.selectedRowKeys), 1)"
    >
      <a-button type="primary">批量还原</a-button>
    </a-popconfirm>
    <a-popconfirm
      cancel-text="取消"
      ok-text="删除"
      title="该操作会永久删除这些博客，是否永久删除?"
      @confirm="deleteFunction(toRaw(state.selectedRowKeys))"
    >
      <a-button danger type="primary">批量删除</a-button>
    </a-popconfirm>
    <a-button>导出</a-button>
  </a-row>
  <a-table
    :columns="columns"
    :data-source="TableData"
    :loading="loading"
    :pagination="pagination"
    :row-selection="{
      selectedRowKeys: state.selectedRowKeys,
      onChange: onSelectChange,
    }"
    style="height: calc(100vh - 270px)"
    @change="handleTableChange"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'cover'">
        <a-image :src="record.cover" :width="200" style="height: 60px" />
      </template>

      <template v-if="column.key === 'editType'">
        <span>
          <a-tag v-if="record.editType === 1" color="success">富文本</a-tag>
          <a-tag v-else color="processing">MarkDown</a-tag>
        </span>
      </template>

      <template v-if="column.key === 'type'">
        <span>
          <i v-if="record.type === 1">原创</i>
          <i v-else>转载</i>
        </span>
      </template>

      <template v-if="column.key === 'status'">
        <span>
          <a-tag v-if="record.status === 1" color="geekblue">正常</a-tag>
          <a-tag v-else color="error">已删除</a-tag>
        </span>
      </template>

      <template v-if="column.key === 'pub_date'">
        <span>
          {{ dayjs(record.pub_date).format("YYYY-MM-DD HH:mm:ss") }}
        </span>
      </template>
      <template v-if="column.key === 'up_date'">
        <span>
          {{ dayjs(record.up_date).format("YYYY-MM-DD HH:mm:ss") }}
        </span>
      </template>

      <template v-if="column.key === 'action'">
        <span style="display: flex; align-items: center; gap: 15px">
          <a-popconfirm
            cancel-text="取消"
            ok-text="删除"
            title="是否删永久除该博客?"
            @confirm="deleteFunction(record.id)"
          >
            <a-button danger>
              <template #icon>
                <DeleteOutlined />
              </template>
            </a-button>
          </a-popconfirm>
          <a-popconfirm
            cancel-text="取消"
            ok-text="还原"
            title="是否还原除该博客?"
            @confirm="reviewFunction(record.id, 1)"
          >
            <a-button>
              <template #icon>
                <ReloadOutlined />
              </template>
            </a-button>
          </a-popconfirm>
        </span>
      </template>
    </template>
  </a-table>
</template>

<script setup>
import {
  DeleteOutlined,
  RedoOutlined,
  ReloadOutlined,
  SearchOutlined,
} from "@ant-design/icons-vue";
import { computed, getCurrentInstance, h, reactive, ref, toRaw } from "vue";
import { delBlog, getBlogDelList, trueDeleteBlog } from "@/api/blog.js";
import dayjs from "dayjs";
import { userStore } from "@/store/modules/user.js";
import { message } from "ant-design-vue";
import { sortAll } from "@/api/sort.js";

const { proxy } = getCurrentInstance();
const user = userStore();
const initSearch = {
  title: "",
  sort: undefined,
};
let searchInfo = reactive({ ...initSearch });

let TableData = ref([]);
// 表单
const formState = reactive({
  sort: "",
  cover: "",
  type: "",
  summary: "",
  title: "",
  editType: "",
  content: "",
});
// 分类数据
const sortList = ref([]);

let loading = ref(true);
const state = reactive({
  selectedRowKeys: [],
});
let total = ref(0);
let current = ref(0);
let pageSize = ref(0);

// 配置项
const columns = [
  {
    title: "封面",
    key: "cover",
    dataIndex: "cover",
    width: 180,
  },
  {
    title: "文章标题",
    key: "title",
    dataIndex: "title",
    width: 150,
  },
  {
    title: "分类",
    key: "sort_name",
    dataIndex: "sort_name",
    width: 200,
  },
  {
    title: "编辑器",
    key: "editType",
    dataIndex: "editType",
  },
  {
    title: "类型",
    key: "type",
    dataIndex: "type",
    width: 150,
  },
  {
    title: "状态",
    key: "status",
    dataIndex: "status",
    width: 150,
  },
  {
    title: "发布时间",
    key: "pub_date",
    dataIndex: "pub_date",
    width: 300,
  },
  {
    title: "更新时间",
    key: "up_date",
    dataIndex: "up_date",
    width: 300,
  },
  {
    title: "操作",
    key: "action",
    width: 300,
  },
];

// 查询博客
const search = async () => {
  loading.value = true;
  if (searchInfo.title === "" && searchInfo.sort === undefined) {
    message.error("查询不能为空");
    return;
  }
  let info = toRaw(searchInfo);
  await get_TableData({ ...info });
};

// 重置查询
const restSearch = async () => {
  loading.value = true;
  Object.assign(searchInfo, initSearch);
  await get_TableData();
};

// 查询table数据
const get_TableData = async (params) => {
  let res = await getBlogDelList({ id: user.user_id, ...params });
  if (!res) return;
  if (res.status === 400) {
    message.error(res.data);
    return;
  }
  TableData.value = res.data.map((item) => ({ ...item, key: item.id }));
  total.value = res.total;
  current.value = res.page;
  pageSize.value = res.pageSize;
  loading.value = false;
};

// 获取所有分类
const get_sortAll = async () => {
  let res = await sortAll();
  if (!res) return;
  sortList.value = res.data;
};

// 勾选删除id
const onSelectChange = (selectedRowKeys) => {
  state.selectedRowKeys = selectedRowKeys;
};

// 删除
const deleteFunction = async (params) => {
  let res = await trueDeleteBlog({ id: params, status });
  await get_TableData();
  message.success(res.data);
};
const reviewFunction = async (params, status = 0) => {
  let res = await delBlog({ id: params, status });
  await get_TableData();
  message.success(res.data);
};

// 分页
const pagination = computed(() => ({
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
  showTotal: (total) => `总共 ${total} 项`,
  defaultPageSize: 10,
  pageSizeOptions: ["5", "10", "15", "20"], // 可不设置使用默认
}));
// 点击分页
const handleTableChange = (pag, filters, sorter) => {
  current.value = pag.current;
  pageSize.value = pag.pageSize;
  get_TableData({ page: current.value, pageSize: pageSize.value });
};

get_TableData();
get_sortAll();
</script>

<style lang="scss" scoped>
.search {
  .btn {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    gap: 15px;
  }
}

.topActive {
  background-color: #63a35c;
  color: #fff;
}
</style>
